package com.jml.juc.BlockingQueue;


class MyCondition{
    private int number = 0;
    //⽼版写法
    public synchronized void increment() throws Exception{
        //1.判断
        while (number != 0){
            this.wait();
        }
        //2.⼲活
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //3通知
        this.notifyAll();
    }
    public synchronized void decrement() throws Exception{
        //1.判断
        while (number == 0){
            this.wait();
        }
        //2.⼲活
        number--;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //3通知
        this.notifyAll();
    }
}
/**
 * 题⽬：现在两个线程，可以操作初始值为零的⼀个变量，
 * 实现⼀个线程对该变量加1，⼀个线程对该变量-1，
 * 实现交替，来10轮，变量初始值为0.
 * 1.⾼内聚低耦合前提下，线程操作资源类
 * 2.判断/⼲活/通知
 * 3.防⽌虚假唤醒(判断只能⽤while，不能⽤if)
 * 知识⼩总结：多线程编程套路+while判断+新版写法
 */
public class ProdConsumerDemo {
    public static void main(String[] args) {
        MyCondition myCondition = new MyCondition();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "师傅A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "顾客A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "师傅B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    myCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "顾客B").start();
    }
}
